package com.wjk.blogs.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Controller
public class mdPicUploadController {

    @RequestMapping("/editormdPicUpload")
    @ResponseBody
    public JSONObject editormdPic(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file,
                                  HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {

        String trueFileName = file.getOriginalFilename();

        String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));

        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;

//        String path = request.getSession().getServletContext().getRealPath("upload");
        String path = "D:/王建凯的毕业设计/blogs/img";
        File targetFile = new File(path, fileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        //保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }


        JSONObject res = new JSONObject();
        //这就是返回给页面的json数据
//        res.put("url", request.getContextPath() + "/upload/" + fileName);
        res.put("url","/img/"+fileName);

        res.put("success", 1);
        res.put("message", "upload success!");

        return res;

    }


}





